<template>
    <div class="create-edit-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="110px">
                <el-form-item label="产品" prop="productNo">
                    <el-select
                        placeholder="请选择产品"
                        @change="productChange"
                        v-model="formData.productNo"
                        :disabled="isEdit()"
                        filterable
                    >
                        <el-option
                            v-for="item in productList"
                            :label="item.productName"
                            :key="item.productNo"
                            :value="item.productNo"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备名称(简称)" prop="deviceName">
                    <el-input
                        v-model="formData.deviceName"
                        @input="value => (formData.deviceName = value.trim())"
                        @change="deviceNameChange"
                        placeholder="请输入设备名称(简称)"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="设备全称">
                    <el-input
                        v-model="formData.deviceFullName"
                        @input="value => (formData.deviceFullName = value.trim())"
                        placeholder="请输入设备全称"
                        maxlength="50"
                    />
                </el-form-item>
                <!-- <el-form-item label="设备简拼">
                    <el-input
                        v-model="formData.deviceBriefName"
                        @input="value => (formData.deviceBriefName = value.trim())"
                        placeholder="请输入设备简拼"
                        maxlength="50"
                    />
                </el-form-item> -->
                <el-form-item label="标识符">
                    <el-input placeholder="系统自动生成" v-model="formData.id" disabled />
                </el-form-item>
                <el-form-item label="设备编号" prop="deviceNo">
                    <el-input
                        v-model="formData.deviceNo"
                        @input="value => (formData.deviceNo = value.trim())"
                        placeholder="请输入设备编号"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="设备标签">
                    <el-tree-select
                        v-model="formData.labels"
                        :data="labelTree"
                        :props="defaultProps"
                        @visible-change="visibleChange"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :render-after-expand="false"
                        show-checkbox
                        node-key="labelNo"
                    />
                </el-form-item>
                <el-form-item label="认证方式" prop="authType">
                    <el-select placeholder="请选择认证方式" v-model="formData.authType">
                        <el-option v-for="(value, key) in AuthType" :label="value" :key="key" :value="key" />
                    </el-select>
                </el-form-item>
                <el-form-item label="组织">
                    <!-- TODO：组织 -->
                    <el-tree-select
                        placeholder="请选择组织"
                        :data="[]"
                        :props="defaultProps"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :render-after-expand="false"
                        show-checkbox
                    />
                </el-form-item>
                <template v-if="currentProduct && currentProduct.productType == 'CLOUD_GATEWAY'">
                    <el-form-item label="NB-IoT串号" prop="nbIotSerial">
                        <el-input
                            v-model="formData.nbIotSerial"
                            @input="value => (formData.nbIotSerial = value.trim())"
                            placeholder="请输入NB-IoT串号"
                            maxlength="50"
                        />
                    </el-form-item>
                    <el-form-item label="NB-IoT注册" prop="nbIotRegistration">
                        <el-input
                            v-model="formData.nbIotRegistration"
                            @input="value => (formData.nbIotRegistration = value.trim())"
                            placeholder="请输入NB-IoT注册"
                            maxlength="50"
                        />
                    </el-form-item>
                </template>
                <template v-if="currentProduct && currentProduct.connectMode == 'PASSIVE'">
                    <el-form-item label="连接方式" style="width: 100%" prop="connectMethod">
                        <el-radio-group v-model="formData.connectMethod">
                            <el-radio v-for="(value, key) in ConnectMethod" :key="key" :label="key">{{
                                value
                            }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <template v-if="formData.connectMethod == 'SerialPort'">
                        <el-form-item label="串口号">
                            <el-input
                                v-model="formData.serialPort"
                                @input="value => (formData.serialPort = value.trim())"
                                placeholder="请输入串口号"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="串口波特率">
                            <el-input
                                v-model="formData.baudRate"
                                @input="value => (formData.baudRate = value.trim())"
                                placeholder="请输入串口波特率"
                                maxlength="50"
                            />
                        </el-form-item>
                    </template>
                    <template v-else>
                        <el-form-item label="IP地址" prop="networkIp">
                            <el-input
                                v-model="formData.networkIp"
                                @input="value => (formData.networkIp = value.replace(/[^0-9.]/g, ''))"
                                placeholder="0.0.0.0"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="端口号" prop="networkPort">
                            <el-input
                                v-model="formData.networkPort"
                                @input="value => (formData.networkPort = +value.replace(/[^0-9]/g, ''))"
                                placeholder="请输入端口号"
                                maxlength="5"
                            />
                        </el-form-item>
                    </template>
                </template>
                <el-form-item label="描述" style="width: 100%; margin-left: 0">
                    <el-input
                        v-model="formData.description"
                        type="textarea"
                        maxlength="200"
                        show-word-limit
                        placeholder="请输入描述"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">{{
                        formData.authType === 'Secret' ? '自动生成密钥' : '确定'
                    }}</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { IoTProductService, IoTDeviceService, runLabelService } from '@great/services';
import type { IotDevice } from '@great/services';
import { reactive, ref } from 'vue';
import { AuthType, ConnectMethod } from '@/utils/constant';
import { useRouter } from 'vue-router';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

interface IProps extends PopupBoxProps {
    row?: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();
const router = useRouter();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '新建设备',
    width: 900,
    detail: undefined
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const formData = reactive<IotDevice>({
    id: undefined,
    productNo: '',
    deviceName: '', //设备简称
    deviceNo: '', // 设备编号
    authType: '', // 认证方式
    deviceFullName: '', // 设备全称
    // deviceBriefName: '', // 简拼
    nbIotSerial: '', //  NB-IoT串号
    nbIotRegistration: '', //  NB-IoT注册
    connectMethod: 'Wired', // 连接方式
    networkIp: '', // 设备网络ip
    networkPort: undefined, // 设备网络端口
    serialPort: '', // 串口号
    baudRate: '', // 串口波特率
    description: '',
    labels: [] // 标签
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules<IotDevice>>({
    productNo: [{ required: true, message: '请选择产品', trigger: ['blur', 'change'] }],
    deviceName: [{ required: true, message: '请输入设备简称', trigger: ['blur', 'change'] }],
    deviceNo: [{ required: true, message: '请输入设备编号', trigger: ['blur', 'change'] }],
    authType: [{ required: true, message: '请选择认证方式', trigger: ['blur', 'change'] }],
    nbIotSerial: [{ required: true, message: '请输入NB-IoT串号', trigger: ['blur', 'change'] }],
    nbIotRegistration: [{ required: true, message: '请输入NB-IoT注册', trigger: ['blur', 'change'] }],
    connectMethod: [{ required: true, message: '请选择连接方式', trigger: ['blur', 'change'] }],
    networkIp: [
        { required: true, message: '请输入IP地址', trigger: ['blur', 'change'] },
        {
            validator: (rule, value, callback) => {
                // IP 验证
                const ipRegex =
                    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                if (ipRegex.test(value)) callback();
                callback(new Error('请输入正确的IP地址'));
            },
            trigger: ['blur']
        }
    ],
    networkPort: [{ required: true, message: '请输入端口号', trigger: ['blur', 'change'] }]
});
const productList = ref<Array<Record<string, string>>>([]);
const currentProduct = ref(); // 当前产品信息
const labelTree = ref();

// 获取产品列表
const getProductList = async () => {
    const res = await IoTProductService.getProductEnableList();
    productList.value = res.data;
    if (formData.productNo) {
        productChange();
    }
};

// 产品切换
const productChange = () => {
    const product = productList.value.find(item => item.productNo === formData.productNo);
    currentProduct.value = product;
};

// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};
// 设备名称（简称）变更触发
const deviceNameChange = () => {
    //
};
const buildFormData = () => {
    const targetData: any = { ...formData };
    if (currentProduct.value && currentProduct.value.productType !== 'CLOUD_GATEWAY') {
        // 非云网关设备，需要删除相关字段
        targetData.nbIotSerial = null;
        targetData.nbIotRegistration = null;
    }
    if (currentProduct.value && currentProduct.value.connectMode == 'PASSIVE') {
        if (formData.connectMethod == 'SerialPort') {
            // 被动连接设备，串口连接，需要删除相关字段
            targetData.networkIp = null;
            targetData.networkPort = null;
        } else {
            // 被动连接设备，有线、无线，需要删除相关字段
            targetData.serialPort = null;
            targetData.baudRate = null;
        }
    } else {
        // 非被动连接设备，需要删除相关字段
        targetData.connectMethod = null;
        targetData.networkIp = null;
        targetData.networkPort = null;
        targetData.serialPort = null;
        targetData.baudRate = null;
    }
    return targetData;
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return IoTDeviceService[isEdit() ? 'editDevice' : 'creatTreeDevice'](buildFormData());
    },
    {
        manual: true,
        onSuccess(res) {
            if (isEdit()) {
                ElNotification({
                    title: '修改成功！',
                    type: 'success'
                });
            } else {
                ElMessageBox.confirm('请继续维护设备的组件信息！', '创建成功', {
                    confirmButtonText: '继续',
                    cancelButtonText: '完成',
                    type: 'success'
                })
                    .then(() => {
                        router.push({
                            name: 'IoT-device-detail',
                            params: {
                                id: res.data[0].id
                            }
                        });
                    })
                    .catch(() => {});
            }
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        valid && run();
        // valid && buildFormData();
    });
};

// 标签下拉框显隐
const visibleChange = (visible: boolean) => {
    if (visible) getLabelTree();
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-deviceLabel' });
    labelTree.value = res.data;
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 打开弹框
const openDialog = () => {
    if (props.row) {
        dialog.title = '修改设备';
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row.id;
        Object.keys(formData).forEach(key => {
            formData[key] = props.row?.[key];
        });
        getLabelTree();
    } else {
        delete formData.id;
    }
};

const init = () => {
    openDialog();
    getProductList();
};
init();
</script>
<style scoped lang="scss">
.create-edit-modal-wrapper {
    .el-form {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
        :deep(.protocol-box) {
            .el-form-item__content {
                display: flex;
                .el-select {
                    flex: 1;
                }
                .el-select + .el-select {
                    margin-left: 10px;
                }
            }
        }
    }
}
</style>
